<template>
  <div class="root">
    <div class="divBox">
      <div class="content-container">
        <!-- 筛选区域 -->
        <div class="filter-container">
          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">核证标准：</span>
              <el-cascader
                v-model="seletedStandard"
                :options="optionsStandard"
                placeholder="请选择"
                clearable
                @change="update"
              ></el-cascader>
            </div>
            <div class="filter-item">
              <span class="filter-label">交易状态：</span>
              <el-cascader
                v-model="seletedStatus"
                :options="optionsOnlines"
                placeholder="请选择"
                clearable
                @change="update"
              ></el-cascader>
            </div>
            <div class="filter-item">
              <span class="filter-label">签发日期：</span>
              <el-date-picker
                v-model="selectDate"
                type="date"
                placeholder="开始日期"
                @change="update"
              ></el-date-picker>
              <span class="date-separator">至</span>
              <el-date-picker
                v-model="selectEndDate"
                type="date"
                placeholder="结束日期"
                @change="update"
              ></el-date-picker>
            </div>
          </div>
          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">项目名称：</span>
              <el-input
                v-model="searchProjectKeyword"
                placeholder="请输入项目名称"
                @input="update"
              ></el-input>
            </div>
            <div class="filter-item">
              <span class="filter-label">方法学：</span>
              <el-input
                v-model="searchMethodKeyword"
                placeholder="请输入方法学"
                @input="update"
              ></el-input>
            </div>
            <div class="filter-item">
              <span class="filter-label">资产状态：</span>
              <el-cascader
                v-model="seletedAssetsStatus"
                :options="optionsAssetStatus"
                placeholder="请选择"
                clearable
                @change="update"
              ></el-cascader>
            </div>
            <div class="filter-item">
              <span class="filter-label">行业类型：</span>
              <el-cascader
                v-model="seletedIndustry"
                :options="optionsIndustory"
                placeholder="请选择"
                clearable
                @change="update"
              ></el-cascader>
            </div>
          </div>
        </div>

        <!-- 我的资产统计 -->
        <div class="myassets-container">
          <div class="myassets-div">
            <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
            <span class="assets-hint">我的碳信用资产：</span>
            <span class="assets-text">{{ totalAssets }} tCO2e</span>
          </div>
          <div class="assets-line"></div>
          <div class="myassets-div">
            <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
            <span class="assets-hint">总估值：</span>
            <span class="assets-text">¥{{ totalValuation }}</span>
          </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-container">
          <el-button type="primary" @click="onUpload">上传</el-button>
          <el-button type="success" @click="onWantToBuy">我想买</el-button>
          <el-button type="warning" @click="onOffline">场外上架</el-button>
          <el-button type="info" @click="insideTransaction">场内交易</el-button>
        </div>

        <!-- 数据表格 -->
        <div class="table-container">
          <el-table
            :data="list"
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="projectName" label="项目名称" min-width="180"></el-table-column>
            <el-table-column prop="carbonMethodologyName" label="采用方法学" min-width="150"></el-table-column>
            <el-table-column prop="industryCodeName" label="类型" min-width="120"></el-table-column>
            <el-table-column prop="total" label="持仓总量(tCO2e)" min-width="140"></el-table-column>
            <el-table-column prop="valuation" label="资产估值(¥)" min-width="120"></el-table-column>
            <el-table-column prop="assetsStatusName" label="资产状态" min-width="100"></el-table-column>
            <el-table-column prop="transactionStatusName" label="交易状态" min-width="100"></el-table-column>
            <el-table-column prop="issuingDate" label="签发日期" min-width="120"></el-table-column>
            <el-table-column label="操作" min-width="220" fixed="right" align="center">
              <template slot-scope="scope">
                <div class="operation-buttons">
                  <el-button 
                    size="mini" 
                    type="text" 
                    icon="el-icon-view" 
                    @click="onView(scope.row)"
                    class="btn-view"
                  >
                    查看
                  </el-button>
                  <el-button 
                    size="mini" 
                    type="text" 
                    icon="el-icon-edit" 
                    @click="onEdit(scope.row)"
                    class="btn-edit"
                  >
                    修改
                  </el-button>
                  <el-button 
                    size="mini" 
                    type="text" 
                    icon="el-icon-delete" 
                    @click="onDelete(scope.row)"
                    class="btn-delete"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="current"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传弹窗 -->
    <carbon-upload
      :dialogFormVisible="uploadDialogVisible"
      :title="uploadTitle"
      :isCredit="true"
      :row="selectedRow"
      :isEdit="isEdit"
      @changeVisible="handleUploadDialogChange"
      @submit="handleUploadSubmit"
    />

    <!-- 我想买弹窗 -->
    <el-dialog
      title="采购单"
      :visible.sync="wantToBuyDialogVisible"
      width="600px"
    >
      <el-form :model="wantToBuyForm" label-width="120px">
        <el-form-item label="机构名称">
          <el-input v-model="wantToBuyForm.institutionName" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系人姓名">
          <el-input v-model="wantToBuyForm.contactsName"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话">
          <el-input v-model="wantToBuyForm.contactsPhone"></el-input>
        </el-form-item>
        <el-form-item label="联系人邮箱">
          <el-input v-model="wantToBuyForm.contactsEmail"></el-input>
        </el-form-item>
        <el-form-item label="交易数量">
          <el-input v-model="wantToBuyForm.tradeQuantity" type="number"></el-input>
        </el-form-item>
        <el-form-item label="资产单位">
          <el-input v-model="wantToBuyForm.assetUnit"></el-input>
        </el-form-item>
        <el-form-item label="资产单价">
          <el-input v-model="wantToBuyForm.assetUnitPrice" type="number"></el-input>
        </el-form-item>
        <el-form-item label="交割时间">
          <el-date-picker
            v-model="wantToBuyForm.deliveryTime"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            v-model="wantToBuyForm.expirationDate"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="wantToBuyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitWantToBuy">提 交</el-button>
      </div>
    </el-dialog>

    <!-- 场外上架弹窗 -->
    <el-dialog
      title="场外上架"
      :visible.sync="offlineDialogVisible"
      width="600px"
    >
      <el-form :model="offlineForm" label-width="120px">
        <el-form-item label="出售数量(tCO2e)">
          <el-input v-model="offlineForm.tradeQuantity" type="number"></el-input>
        </el-form-item>
        <el-form-item label="出售单价(￥)">
          <el-input v-model="offlineForm.assetUnitPrice" type="number"></el-input>
        </el-form-item>
        <el-form-item label="交割时间">
          <el-date-picker
            v-model="offlineForm.deliveryTime"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            v-model="offlineForm.expirationDate"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="交割方式">
          <el-select v-model="offlineForm.deliveryMethod" placeholder="请选择">
            <el-option label="协议转入" value="0190000001"></el-option>
            <el-option label="竞价交易" value="0190000002"></el-option>
            <el-option label="定价交易" value="0190000003"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交割场所">
          <el-select v-model="offlineForm.deliveryExchange" placeholder="请选择">
            <el-option label="全国碳排放权交易中心" value="0170000001"></el-option>
            <el-option label="北京环境交易所" value="0170000002"></el-option>
            <el-option label="上海环境能源交易所" value="0170000003"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="offlineDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOffline">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  loadCarbonCreditPageList,
  getCarbonCreditAssetsTotal,
  addCarbonTradeQuote,
  deleteCarbonCredit
} from '@/api/carbonAssetApi'
import CarbonUpload from './carbonUpload.vue'

export default {
  name: 'Credit',
  components: {
    CarbonUpload
  },
  data() {
    return {
      // 筛选条件
      seletedStandard: [],
      seletedStatus: [],
      seletedAssetsStatus: [],
      seletedIndustry: [],
      selectDate: '',
      selectEndDate: '',
      searchProjectKeyword: '',
      searchMethodKeyword: '',
      
      // 表格数据
      list: [],
      total: 0,
      current: 1,
      pageSize: 10,
      pageCount: 0,
      
      // 统计数据
      totalAssets: 0,
      totalValuation: 0,
      
      // 弹窗控制
      uploadDialogVisible: false,
      wantToBuyDialogVisible: false,
      offlineDialogVisible: false,
      uploadTitle: '上传碳信用',
      selectedRow: {},
      isEdit: false,
      
      // 表单数据
      wantToBuyForm: {
        institutionName: '碳达峰科技有限公司',
        contactsName: '',
        contactsPhone: '',
        contactsEmail: '',
        tradeQuantity: '',
        assetUnit: 'tCO2e',
        assetUnitPrice: '',
        deliveryTime: '',
        expirationDate: '',
        tradeRole: '0280000001',
        publisherId: '1'
      },
      offlineForm: {
        tradeQuantity: '',
        assetUnitPrice: '',
        deliveryTime: '',
        expirationDate: '',
        deliveryMethod: '',
        deliveryExchange: '',
        assetType: '0140000001',
        tradeRole: '0280000002',
        status: '0200000001'
      },
      
      // 字典数据
      optionsStandard: [
        { label: '全部', value: '' },
        { label: 'VCS', value: 'VCS' },
        { label: 'CDM', value: 'CDM' },
        { label: 'CCER', value: 'CCER' }
      ],
      optionsOnlines: [
        { label: '全部', value: '' },
        { label: '可交易', value: '0160000001' },
        { label: '已锁定', value: '0160000002' },
        { label: '已冻结', value: '0160000003' }
      ],
      optionsAssetStatus: [
        { label: '全部', value: '' },
        { label: '正常', value: '0130000001' },
        { label: '锁定', value: '0130000002' },
        { label: '冻结', value: '0130000003' },
        { label: '待审核', value: '0130000004' }
      ],
      optionsIndustory: [
        { label: '全部', value: '' },
        { label: '能源工业', value: '0010000001' },
        { label: '制造业', value: '0010000002' },
        { label: '建筑', value: '0010000003' },
        { label: '交通', value: '0010000004' },
        { label: '农业', value: '0010000005' }
      ]
    }
  },
  mounted() {
    this.getList(1)
    this.getAssetsTotal()
  },
  methods: {
    // 获取列表数据
    getList(page) {
      const data = {
        asc: true,
        current: page,
        size: this.pageSize,
        certificationCriteria: this.seletedStandard[0] || '',
        transactionStatus: this.seletedStatus[0] || '',
        assetsStatus: this.seletedAssetsStatus[0] || '',
        projectScopeCode: this.seletedIndustry[0] || '',
        issuingDateStart: this.selectDate ? this.formatDate(this.selectDate) : '',
        issuingDateEnd: this.selectEndDate ? this.formatDate(this.selectEndDate) : '',
        projectName: this.searchProjectKeyword,
        methodName: this.searchMethodKeyword
      }
      
      loadCarbonCreditPageList(data).then(res => {
        console.log('碳信用列表API响应:', res)
        // 根据实际API响应格式处理数据
        if (res && res.records) {
          this.list = res.records
          this.total = Number(res.total)
          this.current = Number(res.current)
          this.pageCount = Math.ceil(parseInt(res.total) / this.pageSize)
          
          // 处理数据
          this.list.forEach(v => {
            // 处理行业代码名称
            v.industryCodeName = v.industryCodeName || v.projectScopeType || '--'
            // 处理签发日期格式
            if (v.issuingDate) {
              let time = v.issuingDate.split(' ')
              v.issuingDate = time[0]
            }
            // 处理空值
            for (var i in v) {
              if (v[i] === null || v[i] === undefined || v[i] === '') {
                v[i] = '--'
              } else if (v[i] === ' ') {
                v[i] = '--'
              }
            }
          })
        } else {
          console.warn('碳信用数据格式不匹配，使用模拟数据')
          this.loadMockData()
        }
      }).catch(err => {
        console.error('获取碳信用列表失败:', err)
        // 使用模拟数据
        this.loadMockData()
      })
    },
    
    // 加载模拟数据
    loadMockData() {
      this.list = [
        {
          id: 1,
          projectName: '太阳能发电项目',
          carbonMethodologyName: 'CM-001-V01',
          industryCodeName: '能源工业',
          total: 1000,
          valuation: 50000,
          assetsStatusName: '正常',
          transactionStatusName: '可交易',
          issuingDate: '2024-01-15'
        },
        {
          id: 2,
          projectName: '风力发电项目',
          carbonMethodologyName: 'CM-002-V01',
          industryCodeName: '能源工业',
          total: 2000,
          valuation: 100000,
          assetsStatusName: '锁定',
          transactionStatusName: '已锁定',
          issuingDate: '2024-02-20'
        }
      ]
      this.total = this.list.length
      this.totalAssets = 3000
      this.totalValuation = 150000
    },
    
    // 获取资产统计
    getAssetsTotal() {
      getCarbonCreditAssetsTotal().then(res => {
        console.log('资产统计API响应:', res)
        // 根据实际API响应格式处理数据
        if (res && res.total !== undefined) {
          this.totalAssets = Number(res.total) || 0
          this.totalValuation = Number(res.valuation) || 0
        } else {
          console.warn('资产统计数据格式不匹配，使用模拟数据')
          this.totalAssets = 3000
          this.totalValuation = 150000
        }
      }).catch(err => {
        console.error('获取资产统计失败:', err)
        // 使用模拟数据
        this.totalAssets = 3000
        this.totalValuation = 150000
      })
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 更新筛选
    update() {
      this.getList(1)
    },
    
    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val
      this.getList(1)
    },
    
    handleCurrentChange(val) {
      this.current = val
      this.getList(val)
    },
    
    // 选择变化
    handleSelectionChange(selection) {
      console.log('选中的行:', selection)
    },
    
    // 操作按钮
    onUpload() {
      this.uploadTitle = '上传碳信用'
      this.selectedRow = {}
      this.isEdit = false
      this.uploadDialogVisible = true
    },
    
    onWantToBuy() {
      this.wantToBuyDialogVisible = true
    },
    
    onOffline() {
      this.offlineDialogVisible = true
    },
    
    insideTransaction() {
      this.$router.push('/trade/account/exchange')
    },
    
    onView(row) {
      this.$router.push({
        path: '/carbonAssets/assetDetail',
        query: { id: row.id }
      })
    },
    
    onEdit(row) {
      this.uploadTitle = '修改碳信用'
      this.selectedRow = row
      this.isEdit = true
      this.uploadDialogVisible = true
    },
    
    onDelete(row) {
      this.$confirm('确定要删除这条碳信用记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCarbonCredit(row.id).then(res => {
          this.$message.success('删除成功')
          this.getList(this.current)
        }).catch(err => {
          this.$message.error('删除失败')
        })
      })
    },
    
    // 弹窗处理
    handleUploadDialogChange(visible) {
      this.uploadDialogVisible = visible
    },
    
    handleUploadSubmit() {
      this.uploadDialogVisible = false
      this.getList(this.current)
    },
    
    // 提交我想买
    submitWantToBuy() {
      addCarbonTradeQuote(this.wantToBuyForm).then(res => {
        this.$message.success('提交成功')
        this.wantToBuyDialogVisible = false
      }).catch(err => {
        this.$message.error('提交失败')
      })
    },
    
    // 提交场外上架
    submitOffline() {
      addCarbonTradeQuote(this.offlineForm).then(res => {
        this.$message.success('上架成功')
        this.offlineDialogVisible = false
      }).catch(err => {
        this.$message.error('上架失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.root {
  background: #f2f5f7;
}

.divBox {
  margin: 20px;
  background: #ffffff;
  box-shadow: 0px 2px 8px 0px #eaf0f3;
  border-radius: 8px;
}

.content-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.filter-container {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 30px;
  margin-bottom: 10px;
}

.filter-label {
  margin-right: 10px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.date-separator {
  margin: 0 10px;
  color: #666;
}

.myassets-container {
  display: flex;
  flex-direction: row;
  margin: 20px;
  padding: 15px 20px;
  background: #e3f2ec;
  border-radius: 6px;
  align-items: center;
}

.myassets-div {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}

.assets-hint {
  font-weight: 400;
  color: #424c5c;
  margin-right: 6px;
}

.assets-text {
  font-weight: 500;
  color: #24a776;
}

.assets-line {
  margin: 0 20px;
  width: 1px;
  height: 18px;
  border: 1px solid rgba(38, 181, 129, 0.5);
}

.action-container {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  
  .el-button {
    margin-right: 10px;
  }
}

.table-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

/* 操作按钮样式优化 */
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.operation-buttons .el-button {
  margin: 0;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
  font-size: 12px;
  min-width: 50px;
}

.operation-buttons .btn-view {
  color: #409EFF;
}

.operation-buttons .btn-view:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.operation-buttons .btn-edit {
  color: #E6A23C;
}

.operation-buttons .btn-edit:hover {
  background-color: #fdf6ec;
  color: #E6A23C;
}

.operation-buttons .btn-delete {
  color: #F56C6C;
}

.operation-buttons .btn-delete:hover {
  background-color: #fef0f0;
  color: #F56C6C;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .operation-buttons .el-button {
    width: 100%;
    margin: 2px 0;
  }
}
</style>